import akshare as ak
import logging
import pandas as pd
from typing import List,Dict
from datetime import datetime
from core import BaseDataAdapter

logger = logging.getLogger(__name__)

class AKShareFutureAdapter(BaseDataAdapter):
    """商品期货数据适配器"""
    
    def __init__(self,**kwargs)-> None:
        super(AKShareFutureAdapter).__init__(**kwargs)
    @staticmethod
    def format_symbol(symbol: str) -> str:
        return symbol.split('.')[0].lower()

    @classmethod
    async def get_historical_data(cls, symbol: str, start: datetime, end: datetime) -> List[Dict]:
        formatted_symbol = cls.format_symbol(symbol)
        try:
            df = ak.futures_zh_daily_sina(symbol=formatted_symbol)
            return cls.validate_data(df)
        except Exception as e:
            logger.error(f"期货数据获取失败: {str(e)}")
            return []

    @classmethod
    def validate_data(cls, df: pd.DataFrame) -> List[Dict]:
        return [{
            'date': row['date'].strftime("%Y-%m-%d"),
            'open': row['open'],
            'high': row['high'],
            'low': row['low'],
            'close': row['close'],
            'volume': int(row['volume']),
            'open_interest': int(row['open_interest'])
        } for _, row in df.iterrows()]